package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        persistEntities(em);
        displayEntities(em);
        em.close();
        emf.close();
    }
    private static void displayEntities(EntityManager em){
        Query query = em.createQuery("select e from Employee e");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
            employee.setDepartment("Sales");
            System.err.println("---- before refreshing employee ----");
            System.err.println(JSONObject.toJSONString(employee,false));
            em.refresh(employee);
            System.err.println("---- after refreshing employee ----");
            System.err.println(JSONObject.toJSONString(employee,false));
        }
    }
    public static Employee persistEntities(EntityManager em){
        Employee employee = new Employee("Sara Dorsey","Admin");
        em.getTransaction().begin();
        em.persist(employee);
        em.getTransaction().commit();
        return employee;
    }
}
